package controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.gson.Gson;

public class GetInfoSiteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		String url = (String) request.getParameter("url");
		List<String> txt = new ArrayList<String>();
		
		//Get content url
		Document doc = Jsoup.connect(url).get();
		String keywords = "";
		String description = "";
		
		try {
			keywords = doc.select("meta[name=keywords]").first().attr("content");
		} catch (Exception e) {
			try {
				keywords = doc.select("meta[http-equiv=keywords]").first().attr("content");
			} catch (Exception e2) {
			}		
		}
		
		try {
			description = doc.select("meta[name=description]").first().attr("content");
		} catch (Exception e) {
			try {
				description = doc.select("meta[http-equiv=description]").first().attr("content");
			} catch (Exception e2) {
				if(doc.select("body").first().text().length() > 260)
				{
					description = doc.select("body").first().text().substring(0,250).replaceAll("[ ]+[\\w\\W]{0,10}+$", "")+" ...";
				} else {
					description = doc.select("body").first().text();
				}
			}
		}
		
		txt.add(keywords);
		txt.add(description);
		
		String json = new Gson().toJson(txt);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);
	}
}
